package com.cn.web.role.service.impl;

import com.alibaba.fastjson.JSON;
import com.cn.error.ErrorConstantUtil;
import com.cn.exception.MyException;
import com.cn.page.PageVo;
import com.cn.role.RoleDO;
import com.cn.role.RoleMenuDO;
import com.cn.user.UserDO;
import com.cn.user.UserRoleDO;
import com.cn.util.AuthUserContext;
import com.cn.util.GsonUtil;
import com.cn.util.SnowflakeIdWorkerUtil;
import com.cn.web.role.mapper.RoleMapper;
import com.cn.web.role.service.RoleMenuService;
import com.cn.web.role.service.RoleService;
import com.cn.web.role.service.UserRoleService;
import com.cn.web.role.vo.RoleEditDTO;
import com.cn.web.role.vo.RoleSearch;
import com.cn.web.role.vo.RoleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * description: RoleService <br>
 * date: 21.12.16 13:45 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    @Transactional
    public void edit(RoleEditDTO roleEdit) {
        if (StringUtils.isEmpty(roleEdit.getStatus())) {
            roleEdit.setStatus("0");
        }
        //是否子系统管理员
        if (roleEdit.getAdminFlag() == null) {
            roleEdit.setAdminFlag(1);
        }
        UserDO token = AuthUserContext.get();


        RoleDO entity = new RoleDO();
        entity.setId(roleEdit.getId());
        entity.setRoleName(roleEdit.getRoleName()).setRoleDesc(roleEdit.getRoleDesc()).setStatus(roleEdit.getStatus());
        entity.setAddId(token.getId().toString()).setAddName(token.getUserName());
        entity.setDataType(roleEdit.getDataType())
                .setAdminFlag(roleEdit.getAdminFlag());

        if (entity.getId() == null || entity.getId() <= 0) {
            entity.setId(SnowflakeIdWorkerUtil.getId());
            this.roleMapper.insert(entity);
        } else {
            this.roleMapper.update(entity);
        }

        //处理菜单
        //1.删除原来的菜单
        this.roleMenuService.del(entity.getId().toString());
        List<RoleEditDTO.MenuArray> menus = roleEdit.getMenuNo();
        if (menus != null) {
            RoleMenuDO roleMenuEntity = new RoleMenuDO();
            for (RoleEditDTO.MenuArray menu : menus) {
                roleMenuEntity.setId(SnowflakeIdWorkerUtil.getId());
                roleMenuEntity.setRoleId(entity.getId().toString());
                roleMenuEntity.setMenuId(menu.getMenuNo()).setButtons(GsonUtil.toJson(menu.getButtons()));
                this.roleMenuService.add(roleMenuEntity);
            }
        }
    }

    @Override
    public void del(String id) {
        List<UserRoleDO> roles = this.userRoleService.listByRoleId(id);
        if (roles != null && roles.size() > 0) {
            throw new MyException(ErrorConstantUtil.ROLE_USER_ERROR);
        }
        this.roleMapper.deleteById(id);
    }

    @Override
    public PageInfo<RoleVO> page(PageVo<RoleSearch> pageVo) {
        return PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize()).doSelectPageInfo(() -> {
            roleMapper.list(pageVo.getParam());
        });
    }

    @Override
    public List<RoleVO> list(RoleSearch search) {
        return roleMapper.list(search);
    }

    @Override
    public RoleEditDTO find(String id) {
        RoleDO roleEntity = this.roleMapper.selectById(id);
        if (roleEntity == null) {
            throw new MyException(ErrorConstantUtil.ROLE_NO_ERROR);
        }
        RoleEditDTO edit = new RoleEditDTO();
        edit.setId(roleEntity.getId());
        edit.setRoleName(roleEntity.getRoleName()).setRoleDesc(roleEntity.getRoleDesc());
        edit.setStatus(roleEntity.getStatus())
                .setAdminFlag(roleEntity.getAdminFlag());
        edit.setDataType(roleEntity.getDataType())
                .setAddName(roleEntity.getAddName())
                .setAddTime(roleEntity.getAddTime());

        List<RoleMenuDO> roleMenus = this.roleMenuService.list(id);
        if (roleMenus != null) {
            List<RoleEditDTO.MenuArray> menus = new ArrayList<>();
            for (RoleMenuDO roleMenu : roleMenus) {
                RoleEditDTO.MenuArray menuArray = new RoleEditDTO.MenuArray();
                menuArray.setMenuNo(roleMenu.getMenuId()).setButtons(JSON.parseArray(roleMenu.getButtons(), String.class));
                menus.add(menuArray);
            }
            edit.setMenuNo(menus);
        }
        return edit;
    }

    @Override
    public void start(Long id, String status) {
        RoleDO roleEntity = new RoleDO();
        roleEntity.setId(id);
        roleEntity.setStatus(status);
        this.roleMapper.update(roleEntity);
    }

    @Override
    public List<RoleDO> listRoleByAppId(Object pd) {
        return this.roleMapper.listRoleByAppId(pd);
    }
}
